Convert a decimal number to binary number¶
Convert a decimal number to binary number.
Using recursion¶
def decimal_to_binary(N):
if N > 1:
# divide with integral result (discard remainder)
decimalToBinary(N // 2)
print (N % 2, end="")
# test
decimal_to_binary(8) # 1000
print("\r")
decimal_to_binary(18) # 10010
print("\r")
decimal_to_binary(7) # 111
print
Using loop¶
def binary(N):
binary = ""
i = 0
while N > 0 and i <= 8:
s1 = str(int(N % 2))
binary = binary + s1
N /= 2
i = i + 1
d = binary[::-1]
return d
# test
print("The binary representation of 100 (using loops) is : ", end="")
print(binary(100)) # 001100100
Using bin()¶
Using bin() reduces the time required to code and also removes the hassle
that you may see in the above two mentioned methods.
Syntax : bin(a)
Parameters : a : an integer to convert
Return Value : A binary string of an integer or int object.
Exceptions : Raises TypeError when a float value is sent in arguments.
def binary_bin(N):
S = bin(N)
# removing "0b" prefix
S1 = S[2:]
return S1
# test
print("The binary representation of 100 (using bin()) is : ", end="")
print(binary_bin(100)) # 1100100